<template>
  <el-container>
    <el-main class="main-bg">
      <el-form ref="form" :model="form" class="form-list-card-in" label-width="80px">
        <el-form-item v-if="!userInfo.unitId" :required="true" label="部门名称">
          <el-select
            v-model="unitId"
            placeholder="请选择"
            value-key="unitId"
            @change="(val) => onChange(val, 'unitName', 'unitId')"
          >
            <el-option v-for="item in unitList" :key="item.unitName" :label="item.unitName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item v-else :required="true" label="部门名称">
          <el-input v-model="form.unitName" placeholder="请输入" readonly />
        </el-form-item>
        <el-form-item :required="true" label="日期">
          <el-date-picker
            v-model="form.dateTime"
            :picker-options="pickerOptions"
            placeholder="选择日期"
            style="width: 100%"
            type="date"
            value-format="timestamp"
            @change="onChangeTime"
          />
        </el-form-item>
        <el-form-item :required="true" label="类别">
          <el-select
            v-model="sortId"
            placeholder="请选择"
            value-key="sortId"
            @change="(val) => onChange(val, 'sortName', 'sortId')"
          >
            <el-option v-for="item in sortList" :key="item.sortName" :label="item.sortName" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item :required="true" label="所属仓库">
          <el-select
            v-model="warehouseId"
            placeholder="请选择"
            value-key="warehouseId"
            @change="(val) => onChange(val, 'warehouse', 'warehouseId')"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.warehouseName"
              :label="item.warehouseName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="编号">
          <el-input v-model="form.number" placeholder="请输入" readonly />
        </el-form-item>
        <el-form-item label="明细" required>
          <Table
            ref="table"
            :border="true"
            :current-page="page"
            :header-data="form.id ? tableHeader1 : tableHeader"
            :loading="loading"
            :show-pagination="false"
            :span-method="true"
            :table-data="tableData"
            :total="total"
            class="data-table"
            style="width: 100%"
          />
          <el-button class="add-item" size="small" type="primary" @click="onAddItem">增加一行</el-button>
        </el-form-item>
        <el-form-item :required="true" label="备注">
          <el-input v-model="form.remark" maxlength="60" placeholder="请输入" show-word-limit type="textarea" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合计金额">
              <el-input v-model="form.totalAmountChinese" placeholder="请输入" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="¥">
              <el-input v-model="form.totalAmount" placeholder="请输入" readonly>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item :required="true" label="主管">-->
        <!--          <el-input v-model="form.manager" placeholder="请输入"/>-->
        <!--        </el-form-item>-->
        <!--        -->
        <!--        <el-form-item :required="true" label="记账">-->
        <!--          <el-input v-model="form.accountName" placeholder="请输入"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item :required="true" label="经手人">-->
        <!--          <el-input v-model="form.handledName" placeholder="请输入"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <div class="footer">
        <el-button @click="onBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import addTable from "@/mixins/addtable";
import {
  getInBoundDetail,
  getMaxNumber,
  getSortList,
  getUnitList,
  postInBoundAdd,
  postInBoundUpdate,
} from "./api";
import { digitUppercase } from "@/utils";
import { mapGetters } from "vuex";
import { manWithWarehouse } from "@/views/warehouse/api";

export default {
  name: "Inbound",
  mixins: [addTable],
  data () {
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now();
        },
      },
      searchForm: {
        sortName: "",
      },
      tableData: [
        {
          inBoundName: "",
          inBoundType: "",
          inBoundUnitName: "",
          inBoundNum: 0,
          inBoundPrice: 0,
          inBoundMoney: 0,
          // remark: ''
        },
      ],
      unitList: [],
      sortList: [],
      warehouseList: [],
      type: "look",
      tableHeader: [],
      personOptions: [],
      oneLoading: false,
      tableHeader1: [],
      drawerVisible: false,
      unitId: "",
      sortId: "",
      warehouseId: "",
      form: {
        unitId: "",
        unitName: "",
        dateTime: null,
        sortId: "",
        sortName: "",
        number: "",
        totalAmount: 0,
        totalAmountChinese: "",
        manager: "",
        warehouse: "",
        warehouseId: "",
        accountName: "",
        handledName: "",
        remark: "",
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    tableData: {
      handler (val) {
        val.map((item) => {
          item.inBoundMoney = (item.inBoundPrice * item.inBoundNum).toFixed(2);
          return item;
        });
        this.form.totalAmount = val.reduce(
          (accumulator, currentValue) =>
            accumulator + currentValue.inBoundMoney * 1,
          0
        );
        this.form.totalAmount = this.form.totalAmount.toFixed(2);
        this.form.totalAmountChinese = digitUppercase(this.form.totalAmount);
      },
      deep: true,
      immediate: true,
    },
  },
  async created () {
    await this.getInitData();
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id;
      this.getDetail();
    } else {
      this.form.unitName = this.userInfo.unitName;
      this.form.unitId = this.userInfo.unitId;
      this.form.role = this.userInfo.role;
      this.form.userName = this.userInfo.userName;
      this.form.userId = this.userInfo.userId;
      this.form.dateTime = Date.now();
    }
    this.tableHeader1 = [
      {
        prop: "inBoundName",
        label: "名称",
        sortable: false,
        overflow: true,
        width: "300",
        align: "left",
        component: "el-input",
        required: true,
      },
      {
        prop: "inBoundType",
        label: "规格",
        sortable: false,
        overflow: true,
        align: "left",
        component: "el-input",
        required: true,
      },
      {
        prop: "inBoundUnitName",
        label: "单位",
        sortable: false,
        overflow: true,
        align: "left",
        component: "el-input",
        required: true,
      },
      {
        prop: "inBoundNum",
        label: "入库数量",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "inBoundPrice",
        label: "单价",
        sortable: false,
        overflow: true,
        align: "left",
        component: "el-input",
      },
      {
        prop: "inBoundMoney",
        label: "金额",
        sortable: false,
        overflow: true,
        align: "left",
      },
    ];
    this.tableHeader = [
      {
        prop: "inBoundName",
        label: "名称",
        sortable: false,
        overflow: true,
        width: "300",
        align: "left",
        component: "el-input",
        required: true,
      },
      {
        prop: "inBoundType",
        label: "规格",
        sortable: false,
        overflow: true,
        align: "left",
        component: "el-input",
        required: true,
      },
      {
        prop: "inBoundUnitName",
        label: "单位",
        sortable: false,
        overflow: true,
        align: "left",
        component: "el-input",
        required: true,
        // component: 'el-select',
        // options: countUnitList,
        // required: true,
        // listeners: {
        //   change(row, val, $index, config) {
        //     row.inBoundUnitName = config.options.find(item => item.value === row.inBoundUnitName).label
        //   }
        // }
      },
      {
        prop: "inBoundNum",
        label: "入库数量",
        sortable: false,
        overflow: true,
        align: "left",
        component: "el-input",
        required: true,
      },
      {
        prop: "inBoundPrice",
        label: "单价",
        sortable: false,
        overflow: true,
        align: "left",
        component: "el-input",
      },
      {
        prop: "inBoundMoney",
        label: "金额",
        sortable: false,
        overflow: true,
        align: "left",
      },
      // {
      //   prop: 'remark',
      //   label: '备注',
      //   sortable: false,
      //   overflow: true,
      //   align: 'left',
      //   component: 'el-input',
      //   required: true,
      //   attrs: {
      //     type: 'textarea'
      //   }
      // },
      {
        width: 80,
        label: "操作",
        align: "left",
        fixed: "right",
        buttonList: (row, index) => {
          const arr = [];
          if (index !== 0) {
            arr.push({
              text: "删除",
              type: "text",
              event: this.onDelete,
            });
          }
          return arr;
        },
      },
    ];
  },
  methods: {
    getDetail () {
      getInBoundDetail({ id: this.form.id })
        .then((res) => {
          if (!res) return;
          const { data } = res;
          this.form = {
            ...data,
          };
          this.unitId = data.unitId;
          this.sortId = {
            sortId: data.sortId,
            sortName: data.sortName,
          };
          this.warehouseId = {
            warehouseId: data.warehouseId,
            warehouseName: data.warehouseName,
          };
          this.tableData = data.subTable;
        })
        .catch((err) => {
          console.log("TCL: getTableData -> err", err);
        });
    },
    onChange (val, type, id) {
      this.form[type] = val[type];
      this.form[id] = val[id];
      if (id === "warehouseId" && !this.form.id) {
        this.getAjaxMaxNumber();
      }
    },
    onChangeTime (val) {
      if (!this.form.id) {
        this.getAjaxMaxNumber();
      }
    },
    async getAjaxMaxNumber () {
      if (this.form.warehouseId && this.form.dateTime) {
        const { data } = await getMaxNumber({
          warehouseId: this.form.warehouseId,
          dateTime: this.form.dateTime,
        });
        this.form.number = data.newInBoundNo;
      }
    },
    async getInitData () {
      const { data } = await getUnitList({
        page: 1,
        limit: 1000,
      });
      this.unitList = data;
      const res = await getSortList({
        page: 1,
        limit: 1000,
        sortType: "1", // 类型
      });
      this.sortList = res.data;

      const result = await manWithWarehouse();
      this.warehouseList = result.data.map((item) => {
        item.warehouse = item.warehouseName;
        return item;
      });
    },
    onAddItem () {
      if (this.tableData.length >= 5) {
        this.$message.warning("最多只能录入5条记录");
        return;
      }
      this.tableData.push({
        inBoundName: "",
        inBoundType: "",
        inBoundUnitName: "",
        inBoundNum: 0,
        inBoundPrice: 0,
        inBoundMoney: 0,
      });
    },
    onDelete (row, index) {
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.tableData.splice(index, 1);
      });
    },
    onBack () {
      this.$router.back();
    },
    handleSubmit () {
      // //对客户端的数据进行校验
      if (!this.form.unitName) {
        this.$message.error("单位名称不能为空");
        return;
      }
      if (!this.form.dateTime) {
        this.$message.error("日期不能为空");
        return;
      }
      if (!this.form.sortName) {
        this.$message.error("类别名称不能为空");
        return;
      }
      if (!this.form.warehouse) {
        this.$message.error("仓库名称不能为空");
        return;
      }
      if (!this.form.remark) {
        this.$message.error(`明细备注不能为空！`);
        return; // 在验证失败时中断执行
      }
      const regex = /^\d+(\.\d*)?$/; // 修改正则表达式，允许小数点后没有数字
      const fsRegex = /^[-+]?\d*\.?\d+$/;
      for (let i = 0; i < this.tableData.length; i++) {
        const inBoundName = this.tableData[i].inBoundName;
        const inBoundType = this.tableData[i].inBoundType;
        const inBoundUnitName = this.tableData[i].inBoundUnitName;
        const inBoundNum = this.tableData[i].inBoundNum;
        const inBoundPrice = this.tableData[i].inBoundPrice;
        if (!inBoundName) {
          this.$message.error(`明细第${i + 1}行名称不能为空！`);
          return; // 在验证失败时中断执行
        }
        if (!inBoundType) {
          this.$message.error(`明细第${i + 1}行规格不能为空！`);
          return; // 在验证失败时中断执行
        }
        if (!inBoundUnitName) {
          this.$message.error(`明细第${i + 1}行单位不能为空！`);
          return; // 在验证失败时中断执行
        }
        if (!inBoundNum) {
          this.$message.error(`明细第${i + 1}入库数量不能为空！`);
          return; // 在验证失败时中断执行
        }

        if (!regex.test(inBoundPrice)) {
          this.$message.error(`明细第${i + 1}行金额格式不正确！`);
          return; // 在验证失败时中断执行
        }

        if (!fsRegex.test(inBoundNum)) {
          this.$message.error(`明细第${i + 1}行数量格式不正确！`);
          return; // 在验证失败时中断执行
        }
      }
      // if (!this.form.manager) {
      //   this.$message.error('主管不能为空')
      //   return
      // }
      //
      // if (!this.form.accountName) {
      //   this.$message.error('记账不能为空')
      //   return
      // }
      // if (!this.form.handledName) {
      //   this.$message.error('经手人不能为空')
      //   return
      // }
      this.form.id
        ? postInBoundUpdate({ ...this.form, subTable: this.tableData }).then(
          ({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.form = {};
            this.onBack();
          }
        )
        : postInBoundAdd({ ...this.form, subTable: this.tableData }).then(
          ({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.form = {};
            this.onBack();
          }
        );
    },
  },
};
</script>
<style lang="scss">
.form-list-card-in {
  width: 100%;

  .form-list {
    width: 100%;

    .title {
      width: 100%;
      text-align: center;
      font-size: 30px;
      font-weight: bold;
      margin-bottom: 16px;
    }

    .el-col {
      display: flex;
      align-items: center;

      span {
        display: inline-block;
        white-space: nowrap;
        margin: 0 6px;
      }

      .el-input {
        margin: 0 6px;

        .el-input__inner {
          border: none;
        }
      }
    }
  }
}
</style>
